package org.jfk.sys.org;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.jfk.core.model.BaseModel;
import org.jfk.core.model.SqlFilter;
import org.jfk.sys.user.User;

import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Table;
import com.jfinal.plugin.activerecord.TableMapping;

/**
 * 
 * @author jxf
 * 2015年8月21日
 */

@SuppressWarnings("serial")
public class Org extends  BaseModel<Org> {
	private static Logger logger = Logger.getLogger(Org.class);	
	public static final Org dao;
	public static final Table table;
	public static final String tableName;
	static {
		dao = new Org();
		table = TableMapping.me().getTable(Org.class);
		tableName = table.getName();
	}
	
	public Page<Org> paginate(OrgController controller){
		String select = " select "+tableName+".*,ot1.loginName creator_loginName";
		String from =" from "+tableName;
		String join = " left outer join "+User.tableName+" ot1 on ot1.id="+tableName+".creator";
		String where = " where 1=1 ";
		SqlFilter filter = controller.genJsonFilter();
		
		//处理列表查询的智能搜索
		String search = controller.getPara("search");	

		if (search != null && !"".equals(search.trim())) {
			SqlFilter searchFilter = new SqlFilter();
			searchFilter.add("and", tableName+".id", "eq", search);
			searchFilter.add("or", tableName+".groupName", "like", search);
			searchFilter.end();
			filter.add(searchFilter);
			controller.setAttr("search", search);
		}
		
		//加工request参数
		controller.addPageAttr();
		
		String sqlExceptSelect = from+join+where+filter.sqlText;
		sqlExceptSelect = sqlExceptSelect + controller.sqlSort;
		logger.debug(filter);
		Page<Org> page = dao.paginate(controller.currentPage, controller.limit, select, sqlExceptSelect, filter.params.toArray());
		return page;
	}
	
	public Org findById(Object id){
		return dao.findFirst("select a.*,b.loginName creator_loginName"
				+ " from "+tableName+" a "
				+ " left outer join "+User.tableName+" b on a.creator=b.id"
				+ " where a.id=?",id);
	}
	
	
	public List<Org> findAll(){
		return dao.find("select * from "+this.tableName);
	}
	
	public List<Map> findAll4Ztree(){
		List<Org> list = Org.dao.findAll();
		List<Map> ztreeList = new ArrayList();
		for (Org o : list){
			Map m = new HashMap();
			String id = o.get("id").toString();
			Object pId = o.get("pid");
			String _pId = pId == null ? "":pId.toString();
			String name = o.get("orgName");
			m.put("id", id);
			m.put("pId", _pId);
			m.put("name", name);
			ztreeList.add(m);
		}
		return ztreeList;
	}

}
